package com.tuhu.server.web;

import com.tuhu.server.db.DBConn;
import com.tuhu.server.db.op.HeartBeatDB;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.event.ContextClosedEvent;

@SpringBootApplication
@ComponentScans({
        @ComponentScan("com.tuhu.server.web.controller"),
        @ComponentScan("com.tuhu.server.web.filter"),
        @ComponentScan("com.tuhu.server.web.Aspect")
})
@EnableAspectJAutoProxy
public class TuHuApplication {

    public static void main(String[] args) {

        DBConn.getInst();

        SpringApplication app = new SpringApplication(TuHuApplication.class);

        app.addInitializers(new ContextInitializerImpl());
        app.addListeners(new ApplicationListener<ApplicationEvent>() {
            @Override
            public void onApplicationEvent(ApplicationEvent event) {
                if (event instanceof ApplicationReadyEvent) {
                    System.out.println("ContextClosedEvent, 程序就绪");

                    //心跳连接
                    createHeartBeatConn();
                }
                if (event instanceof ContextClosedEvent) {
                    System.out.println("ContextClosedEvent, 程序中止");
                    DBConn.getInst().release();
                }
            }
        });

        //启动 SpringApplication
        ConfigurableApplicationContext context = app.run(args);

        //不需要close
        //context.close();

    }

    //mysql 心跳连接
    private static void createHeartBeatConn() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    int count = HeartBeatDB.heartConn();

                    try {
                        int interval = 1 * 60 * 1000;
                        Thread.sleep(interval);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}
